﻿using System;
using System.Globalization;
using System.Xml;
using System.Xml.Serialization;

namespace Whois.API.Model
{
    public class RegistryData : ModelBase
    {
        [XmlElement(ElementName = "registrant")]
        public Registrant Registrant { get; set; }

        [XmlElement(ElementName = "registrarName")]
        public string RegistrarName { get; set; }

        [XmlElement(ElementName = "createdDate")]
        public string CreatedDateString { get; set; }

        [XmlElement(ElementName = "updatedDate")]
        public string UpdatedDateString { get; set; }
        
        [XmlElement(ElementName = "expiresDate")]
        public string ExpiresDateString { get; set; }

        [XmlElement(ElementName = "strippedText")]
        public string StrippedText { get; set; }

        

        public DateTime? CreatedDate 
        {
            get
            {
                return ParseDateTime(CreatedDateString);
            }
        }

        public DateTime? UpdatedDate
        {
            get
            {
                return ParseDateTime(UpdatedDateString);
            }
        }

        public DateTime? ExpiresDate
        {
            get {
                return ParseDateTime(ExpiresDateString);
            }
        }

        private static DateTime? ParseDateTime(string dateString)
        {
            if (string.IsNullOrEmpty(dateString)) return null;

            DateTime d;
            if (DateTime.TryParse(dateString, out d))
                return d;

            //format that is returned for some domains only
            if (DateTime.TryParseExact(dateString.Trim(), "dd-MMM-yyyy HH:mm:ss UTC", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out d))
                return d;

            //another format: "Thu Jun 12 23:59:59 GMT 2014"
            if (DateTime.TryParseExact(dateString.Trim(), "ddd MMM dd HH:mm:ss GMT yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out d))
                return d;
                
            return null;
        }
    }
}
